package com.fits.auth.api.config;

import com.fits.auth.api.component.JwtTokenEnhancer;
import com.fits.auth.api.constants.ClientEnums;
import com.fits.auth.api.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.builders.InMemoryClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableAuthorizationServer
public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenEnhancer jwtTokenEnhancer;

    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private AuthenticationManager authenticationManager;

    /**
     * OAuth2授权服务器的安全
     *
     * @param security :
     * @author lzy
     * @since 14:59 2024/7/5
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {

        security
                //允许客户端使用基本表单认证来获取令牌
                .allowFormAuthenticationForClients()
                //用于公开暴露 OAuth2 服务端的公钥 /oauth/token_key
                .tokenKeyAccess("permitAll()")
                //用于公开暴露 验证 OAuth2 令牌的有效性 /oauth/check_token
                .checkTokenAccess("permitAll()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        InMemoryClientDetailsServiceBuilder inMemoryClientDetailsServiceBuilder = clients.inMemory();
        for (ClientEnums i : ClientEnums.values()) {
            inMemoryClientDetailsServiceBuilder
                    .withClient(i.getClientId())
                    //进行加密
                    .secret(passwordEncoder.encode("123456"))
                    //授权范围
                    .scopes("all")
                    //令牌过期时间
                    .accessTokenValiditySeconds(i.getExpired())
                    //刷新token的过期时间
                    .refreshTokenValiditySeconds(i.getRefresh())
                    //客户端支持的授权类型
                    .authorizedGrantTypes(i.getGrantType().toArray(new String[0]));
        }
        super.configure(clients);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        List<TokenEnhancer> delegates = new ArrayList<>();
        //jwt 内容增强器
        delegates.add(jwtTokenEnhancer);
        //jwt 内容转换器
        delegates.add(accessTokenConverter());
        //这个有链式token增强，都会调增强方法，最后一个执行完就返回
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(delegates);
        endpoints
                //配置用于验证用户身份的认证管理器
                .authenticationManager(authenticationManager)
                //token
                .tokenEnhancer(tokenEnhancerChain)
                //用户信息和token的转换
                .accessTokenConverter(accessTokenConverter())
                //获取用户信息
                .userDetailsService(userService);
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setKeyPair(keyPair());
        return jwtAccessTokenConverter;
    }

    @Bean
    public KeyPair keyPair() {
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "123456".toCharArray());
        return keyStoreKeyFactory.getKeyPair("Jwt", "123456".toCharArray());
    }
}
